﻿using Microsoft.Extensions.Logging;
using Simple.Framework;
using Simple.Framework.Configuration;
using Simple.Framework.Logger;
using Simple.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.BasicNet.Core.Net
 * 接口名称 CoreNet
 * 开发人员：11920
 * 创建时间：2023/4/7 17:43:30
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace SimpleNet
{
	public class Pretty:IPretty
	{
		protected	Socket pretty;
		[Autowired]
		protected IConfiguration configution { get; set; }	
		[Autowired]
		protected IClientManager clientManager { get;set; }

		[Autowired]
		protected ILogger<Pretty> logger { get; set; }

		public Pretty()
		{
		}
		public virtual void Start()
		{
			Initalization();
			Accept();
		}

		public virtual void Initalization()
		{
			var hostCfg = configution.GetValue<HostConfiguration>("Kernel");
			try
			{//kernel
				IPEndPoint endPoint = new IPEndPoint(hostCfg.GetIpAddress(), hostCfg.Port);
				pretty = new Socket(AddressFamily.InterNetwork, hostCfg.SocketType, hostCfg.ProtocolType);
				pretty.Bind(endPoint);
				pretty.Listen(hostCfg.Backlog);
			}
			catch (Exception ex)
			{

				logger.LogError(ex.Message);
				logger.LogError(ex.StackTrace);
				logger.LogError("请检查服务启动所配置的ip!");
				throw;
			}

			logger.LogInformation("服务器启动成功!");
			logger.LogInformation($"服务器地址{hostCfg.IpAddress}:{hostCfg.Port}");
			logger.LogInformation($"SocketType:{hostCfg.SocketType}\tProtocolType:{hostCfg.ProtocolType}");
		}

		public virtual void Accept()
		{
			Task.Run(() =>
			{
				while (true)
				{
					try
					{
						var client = pretty.Accept();
						var result = clientManager.AddClient(client);
						if (result.Item1)
						{
							logger.LogInformation($"ConnectionID:{result.Item2.ConnectionID}");
							logger.LogInformation($"remoteEndPoint:{client.RemoteEndPoint}");
						}
						else
						{
							logger.LogWarning($"{client.RemoteEndPoint}链接失败!");
							logger.LogWarning($"ID:{result.Item2.ConnectionID}!");
						}
					}
					catch (Exception ex)
					{
						logger.LogError(ex.Message);
						if (ex.InnerException!=null)
						{
							logger.LogError(ex.InnerException.Message);
						}
					}

				}
			});
		}
	}
}
